$(function($){
    // 获取需要用到的元素
    let panelBody=$('.panel-body');
    let username=getCookie('key');
    let nums=document.querySelector('.nums');
    let prices=document.querySelector('.prices');
    // 根据cookie判断是否有登陆
       if(!username){
    localStorage.setItem('url',location.href);
    let strr=confirm('您尚未登陆账号，请先登陆');
    strr?location.href='./login.html': "";
    return; 
    }
    async function getData(){
        let res=await pAjax({
            url:`/self/getCarData.php`,
            data:`username=日薄西山 `
        })
        res=JSON.parse(res);
        console.log(res);
        xuanran(res)
         let good=document.querySelectorAll('.goods');
        goods=good.length;
   
    
    jisuan(goods)
    }
    getData();
    let panel=$('.panel-default');
    let allChecked=document.querySelector('.allChecked')
    
    panel.on('click',function(e){
        console.log($(e.target));
        console.log($('.self'));
        // 实现全选全不选功能
      if(e.target.classList.contains('allChecked')){
        //   $(e.target).attr('checked');
          let chose=e.target.checked;
          console.log(chose);
          console.log(2);
          console.log($('.self'));
          $('.self').attr('checked',chose);
          all();
      }
    //   实现单选功能
     if(e.target.classList.contains('self')){
              let self=document.querySelectorAll('.self');
            
             self=Array.from(self);
              allChecked.checked=self.every(function(item){
            return item.checked;
        })
        all();
       
     
      }
    //   增加商品数量
      if(e.target.classList.contains('add')){
          let num=e.target.previousElementSibling.innerText;
          num++;   
          let idx=e.target.parentNode.parentNode.getAttribute('idx');
          addnum(idx,num)
          
      }
    //   减少商品数量
        if(e.target.classList.contains('reduce')){
          let num=e.target.nextElementSibling.innerText;
          num--;     
          let idx=e.target.parentNode.parentNode.getAttribute('idx');
          addnum(idx,num)
          
      }
    //   删除商品
         if(e.target.classList.contains('del')){
           
          let idx=e.target.parentNode.parentNode.getAttribute('idx');
            delHero(idx)
          
      }
    // 结算功能
  if(e.target.classList.contains('jiesuan')){
      let goods=document.querySelectorAll('.goods');
           goods=Array.from(goods)
            goods=goods.filter(function(item){
                return item.firstElementChild.checked==true;
            })[0];
            if(!goods){
                alert("尚未选择商品");
                return;
            }
      let str=confirm("确定购买该商品吗？")
      if(str==true){
            goods=goods.getAttribute('idx');
            delHero(goods);
           
      }else{
          return;
      }
       
           
          
      }
    // 清空购物车
    if(e.target.classList.contains('qingkong')){
       let res= confirm("确定要清空购物车吗？");
        if(res==true){
            async function clear(){
            let res=await pAjax({
                url:`/self/clearCarData.php`,
                data:`username=${username}`
            })
            getData();
            console.log(res);
        }
        clear();
        }else{
            return;
        }
        
    }
    })
    // 商品的计算函数
   let types=$('.types');
    function jisuan(goods){
        // 商品种类
        types.html(goods)
         }
         function all(){
             // 计算所选商品的总量
        // self.reduce(function(pre,item){
        //     console.log(item);
        //     return pre=item+pre;
        // },0)
        // 计算所选商品的总价
    let self=document.querySelectorAll('.self');
              let shuliang;
              let jiage;
             self=Array.from(self);
              self= self.filter(function(item){
                 return item.checked==true
             })
     
             console.log(1);
           
           shuliang=  self.reduce(function(pre,item){
                    let num= item.parentNode.lastElementChild.firstElementChild.nextElementSibling.innerText*1;
                    return pre=pre+num;
             },0);
             jiage=self.reduce(function(pre,item){
                    let num= item.parentNode.lastElementChild.firstElementChild.nextElementSibling.innerText*1;
                    let price=item.parentNode.lastElementChild.previousElementSibling.firstElementChild.nextElementSibling.lastChild.innerText*1;
                  
                    return pre=pre+num*price;
             },0);
         nums.innerText=shuliang;
         prices.innerHTML=jiage;    
        console.log(self);
         }
       

    // 修改数据的函数
   async function addnum(id,num){
        let res=await pAjax({
            url:`/self/updCarData.php`,
            data:`username=${username}&hero_id=${id}&hero_num=${num}`
        })
      getData();    
    }
    // 删除商品的函数
    async function delHero(id){
         let res=await pAjax({
            url:`/self/removeCarData.php`,
            data:`username=${username}&hero_id=${id}`
        })

      getData(); 
    }
    // 渲染数据的函数
    function xuanran(res){
  panelBody.html(res.map(function(item){
            return `  
            <div class="goods" idx="${item.hero_id}">
                        <input type="checkbox" class='self'>
                        <img src="${item.img}" alt="">
                        <div class="zhong">
                            <p>${item.hero_name}</p>
                            <span>
                                <b class="glyphicon glyphicon-jpy"></b><span>${item.price}</span></span>
                            <button type="button" class="btn btn-danger del">删除商品</button>
                        </div>
                        <p><button class="btn btn-default reduce" type="submit" ${item.hero_num==1?"disabled":""}>-</button>
                            <button type="button" class="btn btn-sm btn-default">
                        ${item.hero_num}
                    </button>
                            <button class="btn btn-default add" type="submit">+</button>
                        </p>
                    </div>`
        }))
    }
})